<?php
//
//  VictoryCMS - Content managment system and framework.
//  Copyright (C) 2009  Lewis Gunsch
//
//  This file is part of VictoryCMS.
//  
//  VictoryCMS is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  VictoryCMS is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//  
//  You should have received a copy of the GNU General Public License
//  along with VictoryCMS.  If not, see <http://www.gnu.org/licenses/>.

/**
 * VictoryCMS - DocumentManager
 * 
 * @license http://www.gnu.org/licenses/gpl.html
 * @author Lewis Gunsch
 * @filesource
 * @package Components
 */

/**
 * 
 * @package Components
 * 
 * @todo Finish implementation & documentation
 */
class DocumentManager extends Component implements DBManager {

	/** The current page the component is on. */
	private $currPage;
	
	/** Folder name field name */
	const FOLDERNAME = "folderName";
	
	/** Folder read permission field name */
	const FOLDERREADPERM = "folderReadPerm";
	
	/** Folder write permission field name */
	const FOLDERWRITEPERM = "folderWritePerm";
	
	/** Folder delete permission field name */
	const FOLDERDELETEPERM = "folderDeletePerm";
	
	/** File name field name */
	const FILENAME = "fileName";
	
	/** File read permission field name */
	const FILEREADPERM = "fileReadPerm";
	
	/** File delete permission field name */
	const FILEDELETEPERM = "fileDeletePerm";
	
	/**
	 * Create a new component instance with instance id $id.
	 *
	 * @param the instance id number.
	 **/
	public function __construct( $id ) {

		$this->name = "DocumentManager";
		$this->id = $id;
		
		$users = new UserLogin();
		$permissions = $users->getPermissionLevel();
		$this->pemList = $permissions->getPermissionListDesc();
	}

	/**
	 * Destroy a component instance, but does not remove
	 * it from the database.
	 */
	public function __destruct() {

	}

	/**
	 * Returns the name of the component.
	 *
	 * @return the component name string.
	 */
	public function getName() {

		return $this->name;
	}

	/**
	 * Sets the current page the component will be rendered on.
	 *
	 * @param String The current page path
	 */
	public function setCurrentPage($currentPage) {

		$this->currPage = $currentPage;
	}


	/**
	 * This is called by the ComponentManager before the page
	 * is rendered.
	 */
	public function componentPreProcess() {
	
		if (!empty($_POST[self::FOLDERNAME])) {
			$folderName = trim($_POST[self::FOLDERNAME]);
			$readPerm = trim($_POST[self::FOLDERREADPERM]);
			$writePerm = trim($_POST[self::FOLDERWRITEPERM]);
			$deletePerm = trim($_POST[self::FOLDERDELETEPERM]);
			if (empty($folderName) || empty($readPerm) || empty($writePerm) || empty($deletePerm)) {
				//TODO: push a message to the user via Messages
				echo "You didn't fill out all the required fields!";
				return;
			}
			try {	
				$perm = new Permission();

				$perm->setPermission($readPerm); // get read permission
				$read = $perm->getPermission();

				$perm->setPermission($writePerm); // get write permission
				$write = $perm->getPermission();
				
				$perm->setPermission($deletePerm); // get delete permission
				$delete = $perm->getPermission();
				
			} catch (PermissionException $e) {
				echo "Caught invalid permission! <br />";
				//TODO: push a message to the user via Messages
				return;
			} catch (Exception $e1) {
				//TODO: push a message to the user via Messages
				echo "Caught something unknown! <br />";
				return;
			}
			
			$db = VcmsDBFactory::createVcmsDb();
			$settings = VcmsSettings::getInstance();
			$prefix = $settings->getDbPrefix();
			$dbname = $settings->getDbName();
			
			$folderParent = "NULL";
			
			// Folder insert query
			$insert = "INSERT INTO ".$prefix."Folder (folder_name, folder_parent, ".
				"folder_write_permission, folder_read_permission, folder_delete_permission) VALUES ";
			$query = sprintf("%s ('%s', %s, '%s', '%s', '%s')", 
				$insert, $db->cleanData($folderName), $folderParent, $write, $read, $delete );
				
			echo $query ."<br />$row<br/>";
				
			$db->runQuery($query);
			
			$row = $db->fetchRow();
			if (!$row) {
				echo "Could not create folder!<br />";
			} 
			
			$db->cleanUp();
		}
	}

	/**
	 * Returns the html of the component. If the users permission
	 * level is not high enough to view this component it will
	 * not be rendered, or may be selectively rendered.
	 *
	 * @return the html string of the component.
	 */
	public function renderComponent() {

		//TODO: finish me.
		$html = "";
		$html .= $this->renderDownloader();
		$html .= $this->renderUploader();

		return $html;
	}
	
	public function renderDownloader() {
		
		$html = "";
		
		// Initialize the html list and form
		$htmlList = new HtmlList();
		$form = new Form($htmlList);
		$form->beginForm("post", $this->currPage, "multipart/form-data");
		
		$form->beginFieldSet("add_fields", "", "", "Add a new folder or upload a file into the current folder.");
		$form->pushLegend("Folder Name", "", "", "", "Add a new folder or upload a file into the current folder.");
		
		$table = new Table($htmlList);
		
		$table->beginTable("", 4, 4, "80%", 1);
		$table->beginRow(array());
		$table->pushTableHeadCell("Name", array());
		$table->pushTableHeadCell("Date", array(''));
		$table->pushTableHeadCell("Size", array(''));
		$table->pushTableHeadCell("&nbsp;", array(''));
		$table->pushTableHeadCell("&nbsp;", array(''));
		$table->endRow();
		$table->endTable();
		
		
		
		$form->endFieldSet();
		$form->endForm();
		
		$html .= $htmlList->render();
		
		return $html;
	}

	/**
	 * This renders the file upload portion of the document manager
	 * to a string and returns the string.
	 *
	 * @return String html of file upload portion
	 */
	protected function renderUploader() {

		$html = "";
		
		// Initialize the html list
		$htmlList = new HtmlList();
		$form = new Form($htmlList);
		$form->beginForm("post", $this->currPage, "multipart/form-data");

		$form->beginFieldSet("add_fields", "", "", "Add a new folder or upload a file into the current folder.");
		$form->pushLegend("Add", "", "", "", "Add a new folder or upload a file into the current folder.");
		
		// main form labels
		$form->pushLabel("folderName", "Folder:&nbsp;", "folderNameLabel", "", "", 
			"Add a new folder into the current folder.");
		$form->pushTextInput(self::FOLDERNAME, self::FOLDERNAME, "", "", "", false, 96, 25);
		
		$this->renderFolderPermChooser($form);
		$form->pushBreak();
		
		// File uploading fields
		$settings = VcmsSettings::getInstance();
		$form->pushHidden("maxFileSize", "MAX_FILE_SIZE", $settings->getMaxFileUpload());
		$form->pushLabel("filePathField", "File:&nbsp;", "filePathLabel", "", "",
			"Upload a file into the current directory.");
		$form->pushFileInput(self::FILENAME, self::FILENAME,"", "", 25);
		
		$this->renderFilePermChooser($form);
		$form->pushBreak();
		
		$form->pushSubmitInput("", "Add");
		$form->endFieldSet();
		$form->endForm();
		
		$html .= $htmlList->render();
		
		return $html;
	}
	
	/**
	 * Creates and initializes an objects database table.
	 *
	 */
	public function setUpDb() {

	}

	/**
	 * Updates an objects database table.
	 */
	public function updateDb() {

	}

	/**
	 * Drops tables and rows associated with this object.
	 */
	public function tearDownDb() {

	}
	
	/**
	 * 
	 * @param $form
	 * @return unknown_type
	 */
	private function renderFolderPermChooser(&$form) {
		
		//TODO: permission level will be moved from UserLogin to Authenticate
		$users = new UserLogin();
		$permissions = $users->getPermissionLevel();
		$pemList = $permissions->getPermissionListDesc();
		
		// Read permission select
		$form->beginSelect(self::FOLDERREADPERM, self::FOLDERREADPERM);
		$form->pushOption("", "", "Read Permission", "", "", "", true, true);
		foreach ($pemList as $key => $name) {
			if ( $permissions->comparePermission($key, true)) {
				$form->pushOption("", "$name", "$name");
			}
		}
		$form->endSelect();
		
		// Write permission select
		$form->beginSelect(self::FOLDERWRITEPERM, self::FOLDERWRITEPERM);
		$form->pushOption("", "", "Write Permission", "", "", "", true, true);
		foreach ($pemList as $key => $name) {
			if ($permissions->comparePermission($key, true)) {
				$form->pushOption("", "$name", "$name");
			}
		}
		$form->endSelect();
		
		// Delete permission select
		$form->beginSelect(self::FOLDERDELETEPERM, self::FOLDERDELETEPERM);
		$form->pushOption("", "", "Delete Permission", "", "", "", true, true);
		foreach ($pemList as $key => $name) {
			if ($permissions->comparePermission($key, true)) {
				$form->pushOption("", "$name", "$name");
			}
		}
		$form->endSelect();
	}
	
	/**
	 * 
	 * @param $form
	 * @return unknown_type
	 */
	private function renderFilePermChooser(&$form) {
		
		$users = new UserLogin();
		$permissions = $users->getPermissionLevel();
		$pemList = $permissions->getPermissionListDesc();
		
		// Read permission select
		$form->beginSelect(self::FILEREADPERM, self::FILEREADPERM);
		$form->pushOption("", "", "Read Permission", "", "", "", true, true);
		foreach ($pemList as $key => $name) {
			if ( $permissions->comparePermission($key, true)) {
				$form->pushOption("", "$name", "$name");
			}
		}
		$form->endSelect();
		
		// Delete permission select
		$form->beginSelect(self::FILEDELETEPERM, self::FILEDELETEPERM);
		$form->pushOption("", "", "Delete Permission", "", "", "", true, true);
		foreach ($pemList as $key => $name) {
			if ($permissions->comparePermission($key, true)) {
				$form->pushOption("", "$name", "$name");
			}
		}
		$form->endSelect();
	}
}
?>
